import PyInstaller.__main__
import os
import sys
import shutil
from build_config import ROOT_DIR, datas, hidden_imports, excludes, binaries

def check_environment():
    """检查环境配置"""
    print("\n检查Python环境...")
    print(f"Python版本: {sys.version}")
    print(f"Python路径: {sys.executable}")
    print(f"工作目录: {os.getcwd()}")
    
def build_exe():
    """构建可执行文件"""
    # 检查环境
    check_environment()
    
    # 确保输出目录存在
    dist_path = os.path.join(ROOT_DIR, "dist")
    build_path = os.path.join(ROOT_DIR, "build")
    
    # 清理旧的构建文件
    for path in [dist_path, build_path]:
        if os.path.exists(path):
            print(f"清理目录: {path}")
            shutil.rmtree(path)
        os.makedirs(path)

    print("\n" + "="*50)
    print(f"开始打包...")
    print(f"项目根目录: {ROOT_DIR}")
    print(f"输出目录: {dist_path}")
    print(f"构建目录: {build_path}")
    print(f"数据文件: {datas}")
    print("="*50 + "\n")

    try:
        # 构建参数
        args = [
            'main.py',
            '--name=成帧数据应用软件',
            '--windowed',
            '--onefile',
            '--clean',
            '--noconfirm',
            '--log-level=DEBUG',
            f'--distpath={dist_path}',
            f'--workpath={build_path}',
            '--runtime-hook=runtime_hook.py'
        ]
        
        # 添加图标（如果存在）
        if os.path.exists('app_icon.ico'):
            args.append('--icon=app_icon.ico')
            
        # 添加数据文件
        for src, dst in datas:
            if os.path.exists(src):
                args.append(f'--add-data={src};{dst}')
            else:
                print(f"警告: 数据文件不存在: {src}")
                
        # 添加二进制文件(.pyd/.dll)
        for src, dst in binaries:
            if os.path.exists(src):
                args.append(f'--add-binary={src};{dst}')
            else:
                print(f"警告: 二进制文件不存在: {src}")
                
        # 添加隐含导入
        for imp in hidden_imports:
            args.append(f'--hidden-import={imp}')
            
        # 添加排除模块
        for exc in excludes:
            args.append(f'--exclude-module={exc}')

        print("PyInstaller参数:")
        for arg in args:
            print(f"  {arg}")
        print("\n开始执行PyInstaller...\n")

        PyInstaller.__main__.run(args)
        
        # 检查结果
        exe_path = os.path.join(dist_path, "成帧数据应用软件.exe")
        if os.path.exists(exe_path):
            print("\n" + "="*50)
            print("打包成功！")
            print(f"可执行文件位置: {exe_path}")
            print(f"文件大小: {os.path.getsize(exe_path) / 1024 / 1024:.2f} MB")
            print("="*50 + "\n")
        else:
            print("\n" + "="*50)
            print("警告：未找到生成的exe文件！")
            print(f"期望的文件位置: {exe_path}")
            
            # 检查警告日志
            warn_log = os.path.join(build_path, "成帧数据应用软件", "warn-成帧数据应用软件.txt")
            if os.path.exists(warn_log):
                print("\n警告日志内容:")
                with open(warn_log, 'r', encoding='utf-8') as f:
                    print(f.read())
                    
            print("="*50 + "\n")
            
    except Exception as e:
        print("\n" + "="*50)
        print(f"打包过程出错: {str(e)}")
        print("="*50 + "\n")
        raise

if __name__ == '__main__':
    build_exe() 